package com.ycg.blog.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.ycg.blog.constants.CacheConstant;
import com.ycg.blog.utils.CacheUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author YCG
 * @date 2024-03-15 16:26
 * @description 统计用户浏览数
 */
@Slf4j
@Component
public class ViewInfoFilter extends OncePerRequestFilter {

    @Resource
    private CacheUtil cacheUtil;

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 定义应该计算的路径
        String[] publicUrls = new String[]{
                "/article/detail",
                "/article/content",
                "/article/about",
                "/article/list"
        };
        String requestURI = request.getRequestURI();
        if (check(publicUrls,requestURI)) {
            cacheUtil.setHash(CacheConstant.SITE_PREVIEW_KEY,"monthViews",
                    String.valueOf(Integer.parseInt(cacheUtil.getHash(CacheConstant.SITE_PREVIEW_KEY,"monthViews"))+1));
            cacheUtil.setHash(CacheConstant.SITE_PREVIEW_KEY,"totalViews",
                    String.valueOf(Integer.parseInt(cacheUtil.getHash(CacheConstant.SITE_PREVIEW_KEY,"totalViews"))+1));
            cacheUtil.setHash(CacheConstant.SITE_PREVIEW_KEY,"yesterdayViews",
                    String.valueOf(Integer.parseInt(cacheUtil.getHash(CacheConstant.SITE_PREVIEW_KEY,"yesterdayViews"))+1));
        filterChain.doFilter(request,response);
        } else {
            filterChain.doFilter(request,response);
        }
    }

    /**
     * 判断请求路径是否包含在制定路径中
     *
     * @param publicUrls
     * @param requestURI
     * @return
     */
    private boolean check(String[] publicUrls, String requestURI) {
        for (String publicUrl : publicUrls) {
            if (PATH_MATCHER.match(publicUrl, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
